package org.jeecg.modules.quality.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.BeanPlusUtil;
import org.jeecg.modules.procurement.entity.BussMaterialProcurement;
import org.jeecg.modules.procurement.vo.BussMaterialProcurementDetailVo;
import org.jeecg.modules.procurement.vo.BussMaterialProcurementPage;
import org.jeecg.modules.quality.vo.BussInspectionFormDetailVo;
import org.jeecg.modules.quality.vo.BussInspectionFormStorageVo;
import org.jeecg.modules.storage.entity.BussStorageNotice;
import org.jeecg.modules.storage.service.IBussStorageNoticeService;
import org.jeecg.modules.storage.vo.BussStorageNoticePage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.quality.entity.BussInspectionFormStorage;
import org.jeecg.modules.quality.entity.BussInspectionFormDetail;
import org.jeecg.modules.quality.entity.BussInspectionForm;
import org.jeecg.modules.quality.vo.BussInspectionFormPage;
import org.jeecg.modules.quality.service.IBussInspectionFormService;
import org.jeecg.modules.quality.service.IBussInspectionFormStorageService;
import org.jeecg.modules.quality.service.IBussInspectionFormDetailService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 检验单
 * @Author: jeecg-boot
 * @Date:   2024-07-09
 * @Version: V1.0
 */
@Api(tags="检验单")
@RestController
@RequestMapping("/quality/bussInspectionForm")
@Slf4j
public class BussInspectionFormController {
	@Autowired
	private IBussInspectionFormService bussInspectionFormService;
	@Autowired
	private IBussInspectionFormStorageService bussInspectionFormStorageService;
	@Autowired
	private IBussInspectionFormDetailService bussInspectionFormDetailService;
	@Autowired
	private  IBussStorageNoticeService bussStorageNoticeService;
	
	/**
	 * 分页列表查询
	 *
	 * @param bussInspectionForm
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "检验单-分页列表查询")
	@ApiOperation(value="检验单-分页列表查询", notes="检验单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BussInspectionFormPage>> queryPageList(BussInspectionForm bussInspectionForm,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BussInspectionForm> queryWrapper = QueryGenerator.initQueryWrapper(bussInspectionForm, req.getParameterMap());
		Page<BussInspectionForm> page = new Page<BussInspectionForm>(pageNo, pageSize);
		IPage<BussInspectionFormPage> pageList = bussInspectionFormService.myPage(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param bussInspectionFormPage
	 * @return
	 */
	@AutoLog(value = "检验单-添加")
	@ApiOperation(value="检验单-添加", notes="检验单-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_inspection_form:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BussInspectionFormPage bussInspectionFormPage,HttpServletRequest req) {
		if(bussInspectionFormPage.getBussInspectionFormStorageList() == null || bussInspectionFormPage.getBussInspectionFormStorageList().size() < 1 ){
			return Result.error("请勾选检验的入库明细！");
		}
		//todo 判断入库单是否进行过修改
		BussStorageNotice noticePage = bussStorageNoticeService.getById(bussInspectionFormPage.getStorageId());
		if(noticePage.getVersion() != bussInspectionFormPage.getVersion()){
			return Result.error("入库单发生变更，请重新选择入库单！");
		}
		BussInspectionForm bussInspectionForm = new BussInspectionForm();
		BeanUtils.copyProperties(bussInspectionFormPage, bussInspectionForm);
		bussInspectionFormService.saveMain(bussInspectionForm, bussInspectionFormPage.getBussInspectionFormStorageList(),bussInspectionFormPage.getBussInspectionFormDetailList(),req,bussInspectionFormPage.getStorageDetailIds());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param bussInspectionFormPage
	 * @return
	 */
	@AutoLog(value = "检验单-编辑")
	@ApiOperation(value="检验单-编辑", notes="检验单-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_inspection_form:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BussInspectionFormPage bussInspectionFormPage) {
		if(bussInspectionFormPage.getBussInspectionFormStorageList() == null || bussInspectionFormPage.getBussInspectionFormStorageList().size() < 1 ){
			return Result.error("请勾选检验的入库明细！");
		}
		//todo 判断入库单是否进行过修改
		BussStorageNotice noticePage = bussStorageNoticeService.getById(bussInspectionFormPage.getStorageId());
		if(noticePage.getVersion() != bussInspectionFormPage.getVersion()){
			return Result.error("入库单发生变更，请重新选择入库单！");
		}
		BussInspectionForm bussInspectionForm = new BussInspectionForm();
		BeanUtils.copyProperties(bussInspectionFormPage, bussInspectionForm);
		BussInspectionForm bussInspectionFormEntity = bussInspectionFormService.getById(bussInspectionForm.getId());
		if(bussInspectionFormEntity==null) {
			return Result.error("未找到对应数据");
		}
		bussInspectionFormService.updateMain(bussInspectionForm, bussInspectionFormPage.getBussInspectionFormStorageList(),bussInspectionFormPage.getBussInspectionFormDetailList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "检验单-通过id删除")
	@ApiOperation(value="检验单-通过id删除", notes="检验单-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_inspection_form:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		bussInspectionFormService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "检验单-批量删除")
	@ApiOperation(value="检验单-批量删除", notes="检验单-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_inspection_form:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.bussInspectionFormService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "检验单-通过id查询")
	@ApiOperation(value="检验单-通过id查询", notes="检验单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BussInspectionForm> queryById(@RequestParam(name="id",required=true) String id) {
		BussInspectionForm bussInspectionForm = bussInspectionFormService.getById(id);
		if(bussInspectionForm==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(bussInspectionForm);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "检验单关联入库明细通过主表ID查询")
	@ApiOperation(value="检验单关联入库明细主表ID查询", notes="检验单关联入库明细-通主表ID查询")
	@GetMapping(value = "/queryBussInspectionFormStorageByMainId")
	public Result<List<BussInspectionFormStorageVo>> queryBussInspectionFormStorageListByMainId(@RequestParam(name="id",required=true) String id) {
		List<BussInspectionFormStorageVo> bussInspectionFormStorageList = bussInspectionFormStorageService.selectByMainId(id);
		return Result.OK(bussInspectionFormStorageList);
	}

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "检验单关联入库明细通过主表ID查询")
	 @ApiOperation(value="检验单关联入库明细主表ID查询", notes="检验单关联入库明细-通主表ID查询")
	 @GetMapping(value = "/queryBussStorageDetail")
	 public Result<List<BussInspectionFormStorageVo>> queryBussStorageDetail(@RequestParam(name="id",required=true) String id,@RequestParam(name="materialId",required=true) String materialId) {
		 List<BussInspectionFormStorageVo> bussInspectionFormStorageList = bussInspectionFormStorageService.selectStorageDetail(id,materialId);
		 return Result.OK(bussInspectionFormStorageList);
	 }
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "质检明细通过主表ID查询")
	@ApiOperation(value="质检明细主表ID查询", notes="质检明细-通主表ID查询")
	@GetMapping(value = "/queryBussInspectionFormDetailByMainId")
	public Result<List<BussInspectionFormDetailVo>> queryBussInspectionFormDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<BussInspectionFormDetailVo> bussInspectionFormDetailList = bussInspectionFormDetailService.selectByMainId(id);
		return Result.OK(bussInspectionFormDetailList);
	}
	 @ApiOperation(value="质检明细主表ID查询不合格", notes="质检明细-通主表ID查询不合格")
	 @GetMapping(value = "/queryBussInspectionFormBhgDetailByMainId")
	 public Result<List<BussInspectionFormDetailVo>> queryBussInspectionFormBhgDetailByMainId(@RequestParam(name="id",required=true) String id) {
		 List<BussInspectionFormDetailVo> bussInspectionFormDetailList = bussInspectionFormDetailService.selectBhgByMainId(id);
		 return Result.OK(bussInspectionFormDetailList);
	 }
	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "质检明细通过主表ID查询")
	 @ApiOperation(value="质检明细主表ID查询", notes="质检明细-通主表ID查询")
	 @GetMapping(value = "/queryStandardsDetail")
	 public Result<List<BussInspectionFormDetailVo>> queryStandardsDetail(@RequestParam(name="id",required=true) String id) {
		 List<BussInspectionFormDetailVo> bussInspectionFormDetailList = bussInspectionFormDetailService.selectStandardsDetail(id);
		 return Result.OK(bussInspectionFormDetailList);
	 }
    /**
    * 导出excel
    *
    * @param request
    * @param bussInspectionForm
    */
    //@RequiresPermissions("org.jeecg.modules.demo:buss_inspection_form:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BussInspectionForm bussInspectionForm) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<BussInspectionForm> queryWrapper = QueryGenerator.initQueryWrapper(bussInspectionForm, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<BussInspectionForm> bussInspectionFormList = bussInspectionFormService.list(queryWrapper);

      // Step.3 组装pageList
      List<BussInspectionFormPage> pageList = new ArrayList<BussInspectionFormPage>();
      for (BussInspectionForm main : bussInspectionFormList) {
          BussInspectionFormPage vo = new BussInspectionFormPage();
          BeanUtils.copyProperties(main, vo);
          List<BussInspectionFormStorageVo> bussInspectionFormStorageList = bussInspectionFormStorageService.selectByMainId(main.getId());
          vo.setBussInspectionFormStorageList(bussInspectionFormStorageList);
          List<BussInspectionFormDetailVo> bussInspectionFormDetailList = bussInspectionFormDetailService.selectByMainId(main.getId());
          vo.setBussInspectionFormDetailList(bussInspectionFormDetailList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "检验单列表");
      mv.addObject(NormalExcelConstants.CLASS, BussInspectionFormPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("检验单数据", "导出人:"+sysUser.getRealname(), "检验单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("org.jeecg.modules.demo:buss_inspection_form:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<BussInspectionFormPage> list = ExcelImportUtil.importExcel(file.getInputStream(), BussInspectionFormPage.class, params);
              for (BussInspectionFormPage page : list) {
                  BussInspectionForm po = new BussInspectionForm();
                  BeanUtils.copyProperties(page, po);
//                  bussInspectionFormService.saveMain(po, page.getBussInspectionFormStorageList(),page.getBussInspectionFormDetailList(),request);
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 @GetMapping("/revokeBatch")
	 public Result<String> revokeBatch(@RequestParam(name="ids",required=true) String ids){
		 this.bussInspectionFormService.revokeBatch(Arrays.asList(ids.split(",")));
		 return Result.OK("撤销成功");
	 }
}
